package com.android.sq.zouqi.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/*
 * 从一个Http请求中获取HttpEntity对象，然后根据请求的类型（这要一句PHP脚本的返回类型），
 * 如果是单纯的String，就调用getString即可
 * 如果是一个对象，比如是Event，就调用getObject(), 
 * 但需要转换pTableEventInfo e = <pTableEventInfo>(getServerData.getString());
 */
public class ServerData {
	private final static String TAG = "ServerData";
	private String url;
	private List<BasicNameValuePair> params;
	private HttpEntity entity = null;
	private HttpClient client;
	private String json_str;
	public ServerData(String url) {
		this.url = url;
		client = new DefaultHttpClient();
	}
	public ServerData(String url, List<BasicNameValuePair> params) {
		//Log.e("ServerData", "ServerData Constructor");
		this.url = url;
		this.params = params;
		client = new DefaultHttpClient();
		//getEntity();
	}
	
	public String getResultString() {
		getEntity();
		String result = "";
		if (entity != null) {
			try {
				result = EntityUtils.toString(entity);
				//Log.e(TAG, "getResultString:result = " + result);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		result = result.trim();
		Log.e(TAG, "ServerData->获取到服务器‘普通字符串’结果: = " + result);
		return result;
	}
	
	public HttpEntity getEntity() {
		HttpPost httpRequest = new HttpPost(url);
		HttpResponse httpResponse;
		try {
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			httpResponse = client.execute(httpRequest);
			int status_code = httpResponse.getStatusLine().getStatusCode();
			Log.e(TAG, "status_code = " + status_code);
			if (status_code == HttpURLConnection.HTTP_OK) {
				entity = httpResponse.getEntity();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			client.getConnectionManager().shutdown();
			httpResponse = null;
		}
		return entity;
	}
	
	public String getResultJsonString() {
		HttpPost httpRequest = new HttpPost(url);
		HttpResponse httpResponse;
		try {
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			httpResponse = client.execute(httpRequest);
			int status_code = httpResponse.getStatusLine().getStatusCode();
			if (status_code == HttpURLConnection.HTTP_OK) {
				entity = httpResponse.getEntity();
				BufferedReader reader = null;
				try {
					InputStream is = entity.getContent();
					reader = new BufferedReader(new InputStreamReader(is));
					StringBuilder sb = new StringBuilder();
					try {
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						reader.close();
						json_str = sb.toString().trim();
						json_str = json_str.substring(1, (json_str.length() - 1));
						json_str = json_str.replace("\\\"", "\"");
						//Log.e(TAG, "GetResultJsonString, JSON_STR = " + json_str.length());
					} catch (IOException e) {
						e.printStackTrace();
					} 
				} catch (UnsupportedEncodingException e) {
					Log.e(TAG, "UnsupportedEncodingException");
					e.printStackTrace();
				} catch (IllegalStateException e) {
					Log.e(TAG, "IllegalStateException");
					e.printStackTrace();
				} catch (IOException e) {
					Log.e(TAG, "IOException");
					e.printStackTrace();
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			client.getConnectionManager().shutdown();
			httpResponse = null;
		}
		return json_str;
	}
	
	/*
	 * 先前的版本，有问题
	 */
	public String getResultJsonString1() {
		//Log.e("BA", "Json2Lv convertStreamToString");
		getEntity();
		BufferedReader reader = null;
		try {
			Log.e("SD", "entity.getContent");
			InputStream is = entity.getContent();
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			//reader = new BufferedReader(new InputStreamReader(is));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			Log.e(TAG, "UnsupportedEncodingException");
			e1.printStackTrace();
		} catch (IllegalStateException e) {
			Log.e(TAG, "IllegalStateException");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e(TAG, "IOException");
			e.printStackTrace();
		}
		StringBuilder sb = new StringBuilder();
		try {
			
			if (reader == null) {
				Log.e(TAG, "READER IS NULL");
			}
			Log.e(TAG, "reader.toString = " + reader.toString());
			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
				// Log.e("SD", "sb.append(" + s + ")");
				sb.append(s);
			}
			reader.close();
			json_str = sb.toString().trim();
			json_str = json_str.substring(1, (json_str.length() - 1));
			json_str = json_str.replace("\\\"", "\"");
			Log.e("SD", "GetResultJsonString, JSON_STR = " + json_str.length());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//Log.e("BA", "SB APPEND S");
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		} 
		return json_str;
	}
 	
	/*
	 * 一个Object泛对象，再获取时需要转换到自己需要的类型
	 */
	/*public T getObject() {
		T object;
		getJsonString();
		Type listType = new TypeToken<LinkedList<T>>() {}.getType();
		Log.e("BA", "list type = " + listType.toString());
		Gson gson = new Gson();
		LinkedList<T> objects = gson.fromJson(json_str, listType);
		// 只需获取一个即可，不用使用迭代器Iterator
		//object = objects.getFirst();
		
		Iterator<T> iterator = objects.iterator();
		object = iterator.next();
		return object;
	}*/

	public void setParams(List<BasicNameValuePair> params) {
		this.params = params;
	}
}
